package client

import (
	"context"
	user "enjoy-joy/common/proto"
	"google.golang.org/grpc"
)

type Handler func(ctx context.Context, in user.UserClient) (interface{}, error)

func UserClient(ctx context.Context, handler Handler) (interface{}, error) {
	dial, err := grpc.Dial("127.0.0.1:8082", grpc.WithInsecure())
	if err != nil {
		return nil, err
	}
	client := user.NewUserClient(dial)
	res, err := handler(ctx, client)
	if err != nil {
		return nil, err
	}
	return res, nil
}
func SendSms(ctx context.Context, i *user.SendSmsReq) (*user.SendSmsResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		sms, err := in.SendSms(ctx, i)
		if err != nil {
			return nil, err
		}
		return sms, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.SendSmsResp), nil
}
func UserLoginOrRegister(ctx context.Context, i *user.UserLoginOrRegisterReq) (*user.UserLoginOrRegisterResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		register, err := in.UserLoginOrRegister(ctx, i)
		if err != nil {
			return nil, err
		}
		return register, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.UserLoginOrRegisterResp), nil
}
func ClassList(ctx context.Context, i *user.ClassListReq) (*user.ClassListResp, error) {
	client, err := UserClient(ctx, func(ctx context.Context, in user.UserClient) (interface{}, error) {
		list, err := in.ClassList(ctx, i)
		if err != nil {
			return nil, err
		}
		return list, nil
	})
	if err != nil {
		return nil, err
	}
	return client.(*user.ClassListResp), nil
}
